package com.ruoyi.carton.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    private static final String[] patterns = {
            "yy-MM-dd HH:mm",
            "yyyy-MM-dd HH:mm",
            "yy/MM/dd HH:mm",
            "yyyy/MM/dd HH:mm",
            "yy-MM-dd",
            "yyyy-MM-dd"
    };

    /**
     * 解析日期字符串，自动修正两位数年份为 2000+
     * @param dateStr 输入的日期字符串，如 "25-06-01 15:54"
     * @return 解析后的 Date 对象
     * @throws RuntimeException 如果无法解析则抛异常
     */
    public static Date parseDate(String dateStr) {
        for (String pattern : patterns) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                sdf.setLenient(false);
                Date date = sdf.parse(dateStr);

                // 修正年份
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                int year = cal.get(Calendar.YEAR);
                if (year < 100) {
                    cal.set(Calendar.YEAR, year + 2000);
                    date = cal.getTime();
                }
                return date;
            } catch (ParseException ignored) {
            }
        }
        throw new RuntimeException("无法解析日期字符串: " + dateStr);
    }
}
